package org.lex.jdbc.url.persist;

import java.io.IOException;
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;

import org.lex.jdbc.url.CommonObject;
import org.lex.jdbc.url.DriverConfig;
import org.lex.jdbc.url.persist.xml.XmlDaoHelper;

public abstract class AbstractDriverDaoImpl implements IDriverDao {

	public List<DriverConfig> getSystemDrivers() {
		List<DriverConfig> results = new ArrayList<DriverConfig>();
		for (Enumeration<Driver> drivers = DriverManager.getDrivers(); drivers
				.hasMoreElements();) {
			Driver driver = drivers.nextElement();
			Class<?> clz = driver.getClass();
			DriverConfig dc = new DriverConfig();
			dc.setClassName(clz.getName());
			dc.setDescription("System JDBC driver");
			dc.setName(clz.getSimpleName());
			dc.setWebsite("http://java.sun.com");
			results.add(dc);
		}
		return results;
	}

	@Override
	public DriverConfig getDriverByName(String driverName) throws IOException {
		DriverConfig driver = CommonObject.getObjectByName(
				this.getSystemDrivers(), driverName);
		if (null == driver) {
			driver = CommonObject.getObjectByName(this.getUserDrivers(),
					driverName);
		}
		return driver;
	}

	@Override
	public DriverConfig getDriverByClassName(Class<? extends Driver> className)
			throws IOException {
		return this.getDriverByClassName(className.getName());
	}

	@Override
	public DriverConfig getDriverByClassName(String className)
			throws IOException {
		DriverConfig dc = this.findDriverByClassName(this.getSystemDrivers(),
				className);
		if (null == dc) {
			dc = this.findDriverByClassName(this.getUserDrivers(), className);
		}
		return dc;
	}

	@Override
	public boolean contains(String className) throws IOException {
		return null != this.getDriverByClassName(className);
	}

	protected DriverConfig findDriverByClassName(
			Collection<DriverConfig> drivers, String className) {
		DriverConfig result = null;
		for (DriverConfig d : drivers) {
			if (className.equals(d.getClassName())) {
				result = d;
				break;
			}
		}
		return result;
	}
}
